package com.motu.monstercity.server.game.logichandler;

import com.motu.monstercity.module.common.network.RequestParam;
import com.motu.monstercity.module.common.servermanager.ServerInfo;
import com.motu.monstercity.module.common.servermanager.ServerManager;
import com.motu.monstercity.protocol.Common.PBRankMember;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.protocol.CsGameRankact.*;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.CommonUtils;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.act.ActConfig;
import com.motu.monstercity.server.game.commondata.act.ActRechargeTask;
import com.motu.monstercity.server.game.commondata.act.ActTask;
import com.motu.monstercity.server.game.commondata.act.ActTopRanking;
import com.motu.monstercity.server.game.commondata.rank.RankReward;
import com.motu.monstercity.server.game.commondata.shop.Shop;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.logic.*;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.redis.RedisTools;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public class RankactHandler {

    public static void updateRankActData(PBUserData.Builder pbUserData, long userId, ActConfig actConfig, boolean loadTask) {
        UserRankAct userActTopRank = RankActManager.getUserRankAct(userId, 1, actConfig.getConfigId());
        if (null == userActTopRank && loadTask) {
            userActTopRank = new UserRankAct(userId, 1, actConfig.getConfigId());
            userActTopRank.doCreate();
        }
        if (userActTopRank != null) {
            ProtoDataUtils.updatePBUserData(pbUserData, userActTopRank, true);
        }
        if (loadTask) {
            List<UserRankActTask> taskList = RankActManager.getRankActTaskList(userId, actConfig.getConfigId());
            for (UserRankActTask task : taskList) {
                ProtoDataUtils.updatePBUserData(pbUserData, task, true);
            }
            List<UserRechargeActTask> rechargeActTaskList = RankActManager.getUserRechargeActTaskList(userId, actConfig.getConfigId());
            for (UserRechargeActTask task : rechargeActTaskList) {
                ProtoDataUtils.updatePBUserData(pbUserData, task, true);
            }
            List<UserRankActShop> shopList = RankActManager.getUserRankActShopList(userId, actConfig.getConfigId());
            for (UserRankActShop shop : shopList) {
                ProtoDataUtils.updatePBUserData(pbUserData, shop, true);
            }
        }
    }

    public static void updateCrossRankActData(PBUserData.Builder pbUserData, long userId, int configId, long round, boolean checkRound) {
        ActConfig actConfig = RankActManager.getActConfig(configId);
        if (actConfig != null) {
            UserCrossRankAct userActTopRank = RankActManager.getUserCrossRankAct(userId, actConfig.getConfigId());
            if (checkRound && userActTopRank == null) {
                userActTopRank = new UserCrossRankAct(userId, actConfig.getConfigId(), round);
                userActTopRank.doCreate();
            }
            if (userActTopRank != null) {
                if (checkRound) {
                    userActTopRank.checkReset(round);
                }
                ProtoDataUtils.updatePBUserData(pbUserData, userActTopRank, true);
            }
            if (checkRound) {
                List<UserCrossRankActTask> taskList = RankActManager.getUserCrossRankActTaskList(userId, configId);
                for (UserCrossRankActTask task : taskList) {
                    if (task.getRound() == round) {
                        ProtoDataUtils.updatePBUserData(pbUserData, task, true);
                    }
                }
                List<UserCrossRechargeActTask> rechargeActTaskList = RankActManager.getUserCrossRechargeActTaskList(userId, configId);
                for (UserCrossRechargeActTask task : rechargeActTaskList) {
                    if (task.getRound() == round) {
                        ProtoDataUtils.updatePBUserData(pbUserData, task, true);
                    }
                }
                List<UserCrossRankActShop> shopList = RankActManager.getUserCrossRankActShopList(userId, configId);
                for (UserCrossRankActShop shop : shopList) {
                    if (shop.getRound() == round) {
                        ProtoDataUtils.updatePBUserData(pbUserData, shop, true);
                    }
                }
            }
        }
    }

    // CMD_GAME_RANKACT_INFO = 73201; // 活动信息
    public static Object CMD_GAME_RANKACT_INFO(RequestParam clientParam) throws Exception {
        CSGameRankactInfoResponse.Builder response = CSGameRankactInfoResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        ServerInfo serverInfo = ServerManager.getServerInfo(userInfo.getServerId());
        int localDays = RankActManager.getActDays(ActConfig.GROUP_ID_LOCAL);
        long curTime = TimeUtils.getCurTime();
        long today = TimeUtils.getStartTimeOfDay(curTime);
        int serverOpenDays = TimeUtils.getDiffDay(serverInfo.getStartTime(), curTime) + 1;
        PBUserData.Builder pbUserData = response.getUserBuilder();
        if (serverOpenDays <= localDays) { // 本服活动
            response.setActGroupId(ActConfig.GROUP_ID_LOCAL);
            response.setStatus(1);
            ConcurrentHashMap<Integer, ActConfig> actConfigMap = RankActManager.getActConfigList(ActConfig.GROUP_ID_LOCAL);
            ActConfig actConfig = RankActManager.getActConfig(serverOpenDays, actConfigMap, false);
            if (actConfig != null) {
                updateRankActData(pbUserData, userId, actConfig, true);
                long[] times = actConfig.getConfigTime(ActConfig.GROUP_ID_LOCAL, serverInfo.getStartTime(), curTime);
                response.setStartTime(times[0]);
                response.setEndTime(times[1]);
                response.setConfigId(actConfig.getConfigId());
            }
            long yesterday = today - TimeUtils.DAY;
            int lastLocalday = TimeUtils.getDiffDay(serverInfo.getStartTime(), yesterday) + 1;
            ConcurrentHashMap<Integer, ActConfig> actConfigMap1 = RankActManager.getActConfigList(ActConfig.GROUP_ID_LOCAL);
            ActConfig actConfig1 = RankActManager.getActConfig(lastLocalday, actConfigMap1, true);
            if (actConfig1 != null) {
                updateRankActData(pbUserData, userId, actConfig1, false);
                long[] times = actConfig1.getConfigTime(ActConfig.GROUP_ID_LOCAL, serverInfo.getStartTime(), yesterday);
                response.setLastRankEndTime(times[1]);
//                response.setLastRankRewardTime(times[2]);
            }
        } else {
            long yesterday = today - TimeUtils.DAY;
            int lastLocalday = TimeUtils.getDiffDay(serverInfo.getStartTime(), yesterday) + 1;
            if (lastLocalday == localDays) { // 本服活动最后一天
                ConcurrentHashMap<Integer, ActConfig> actConfigMap = RankActManager.getActConfigList(ActConfig.GROUP_ID_LOCAL);
                ActConfig actConfig = RankActManager.getActConfig(lastLocalday, actConfigMap, true);
                if (actConfig != null) {
                    updateRankActData(pbUserData, userId, actConfig, false);
                    long[] times = actConfig.getConfigTime(ActConfig.GROUP_ID_LOCAL, serverInfo.getStartTime(), yesterday);
                    response.setLastRankEndTime(times[1]);
//                    response.setLastRankRewardTime(times[2]);
                }
            }
            response.setActGroupId(ActConfig.GROUP_ID_GLOBAL);
            JsonObject param = RankActManager.isCrossRankAct(curTime);
            response.setStatus(2);
            if (null != param) { // 跨服活动
                String stimeDay = param.getString("stimeDay");
                long round = param.getLong("round");
                int configId = param.getInteger("actid");
                long stime = param.getLong("stime", 0L);
                long etime = param.getLong("etime");
                RankActGroup rankActGroup = RankActManager.getRankActGroup(serverInfo.getWarZone(), round);
                if (rankActGroup != null) {
                    JsonArray serverList = rankActGroup.getServerListArray();
                    if (Tool.isInList(serverList, userInfo.getServerId())) {
                        response.setStatus(1);
                        updateCrossRankActData(pbUserData, userId, configId, round, true);
                        response.setConfigId(configId);
                    }
                }
                response.setStartTime(stime);
                response.setEndTime(etime);
                JsonObject lastConfig = RankActManager.isCrossRankAct(yesterday);
                if (lastConfig != null && today >= lastConfig.getLong("etime")) { // 跨服活动最后一天
//                    String yStimeDay = lastConfig.getString("stimeDay");
                    long yRound = lastConfig.getLong("round");
                    int topId = lastConfig.getInteger("actid");
                    long endTime = lastConfig.getLong("etime");
                    long closeTime = lastConfig.getLong("closetime");
                    updateCrossRankActData(pbUserData, userId, topId, yRound, false);
                    response.setLastRankEndTime(endTime);
//                    response.setLastRankRewardTime(closeTime);
//                    long stime1 = param.getLong("stime", 0L);
//                    RankActGroup yRankActGroup = RankActManager.getRankActGroup(serverInfo.getActGroup(), yRound);
//                    if (yRankActGroup != null) {
//                        if (yRankActGroup.containsServer(userInfo.getServerId())) {
//                        }
//                    }
                }
            }
        }
        return response;
    }

    // CMD_GAME_RANKACT_RANK_LIST = 73202; // 单服活动榜单
    public static Object CMD_GAME_RANKACT_RANK_LIST(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        CSGameRankactRankListRequest request = CSGameRankactRankListRequest.parseFrom(clientParam.getData());
        int configId = request.getConfigId();
        int type = request.getType();
        ServerInfo serverInfo = ServerManager.getServerInfo(userInfo.getServerId());
        CSGameRankactRankListResponse.Builder response = CSGameRankactRankListResponse.newBuilder();
        int serverId = serverInfo.getServerId();
        long curTime = TimeUtils.getCurTime();
        ActConfig actConfig = RankActManager.getActConfig(configId);
        if (actConfig == null || actConfig.getGroupId() != ActConfig.GROUP_ID_LOCAL) {
            return ErrorWord.TIMES_LACK; // 活动已结束
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (type == ActTopRanking.RANK_TYPE_UNION_EXP && userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_3;
        }
        long rankId = RankActManager.getRankId(configId, (byte) type);

        long[] time = actConfig.getConfigTime(serverInfo.getWarZone(), serverInfo.getStartTime(), curTime);//获取活动的开始时间和结束时间
        long actStarttime = time[0]; //活动的开始时间
        long round = 1;
        String rankName = RankActManager.getServerActRankKey(rankId, serverId, round);
        Long myRank = null;
        Double myScore = null;
        if (type == ActTopRanking.RANK_TYPE_UNION_EXP) {
            myRank = Future.await(RedisTools.getMyRank(rankName, String.valueOf(userUnion.getUnionId())));
            myScore = Future.await(RedisTools.getMyScore(rankName, userUnion.getUnionId()));
        } else {
            myRank = Future.await(RedisTools.getMyRank(rankName, userId + ""));
            myScore = Future.await(RedisTools.getMyScore(rankName, userId));
        }
        response.setMyRank(myRank.intValue());
        if (myRank > 0) {
            response.setMyScore(RankManager.getTrueScore(myScore));
        }
        ActTopRanking ranking = RankActManager.getActTopRankingByType(actConfig.getRankList(), type);
        if (ranking == null) {
            return ErrorWord.BAD_PARAM;
        }
        UserActTopRank userActTopRank = RankActManager.getUserActTopRank(userId, rankId);
        if (userActTopRank != null) {
            response.setMyMaxScore(userActTopRank.getMaxScore());
        }
        JsonArray list = Future.await(RedisTools.getRankListByIndex(rankName, 0, ranking.getList() - 1, true));

        JsonArray uidArray = new JsonArray();// userid 列表
        for (int i = 0; i < list.size(); i++) {// userid,分数,userid,分数
            if (i % 2 == 0) {// userid
                uidArray.add(list.getString(i));
            }
        }
        for (int i = 0; i < list.size(); i++) {
            if (i % 2 == 0) {// userid
                String uidStr = list.getString(i);
                long uid = Long.parseLong(uidStr);// 用户id
                double score = RankManager.getTrueScore(Double.parseDouble(list.getString(i + 1)));
                if (score > 0) {// 负数和0不下发
                    PBRankMember.Builder rankMember = null;
                    if (type == ActTopRanking.RANK_TYPE_UNION_EXP) {
                        rankMember = RankActManager.getUnionRankMember(uid, score);
                    } else {
                        rankMember = RankActManager.getRankMember(uid, score);
                    }
                    response.addRankList(rankMember);
                }
            }
        }

        return response;
    }

    // CMD_GAME_RANKACT_MYRANKS = 73203; // 读取榜单中所有冲榜活动中我的排名
    public static Object CMD_GAME_RANKACT_MYRANKS(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        CSGameRankactMyranksRequest request = CSGameRankactMyranksRequest.parseFrom(clientParam.getData());
        int configId = request.getConfigId();
        CSGameRankactMyRanksResponse.Builder response = CSGameRankactMyRanksResponse.newBuilder();
        long curTime = TimeUtils.getCurTime();
        ServerInfo serverInfo = ServerManager.getServerInfo(userInfo.getServerId());
        ActConfig actConfig = RankActManager.getActConfigByTopId(ActConfig.GROUP_ID_LOCAL, configId);
        if (actConfig == null) {
            return ErrorWord.WRONG_STATUS;
        }
        List<ActTopRanking> topRankingList = RankActManager.getActTopRankingList(actConfig.getConfigId());
        if (topRankingList == null || topRankingList.isEmpty()) {
            return ErrorWord.NOT_DATA;
        }
        long[] time = actConfig.getConfigTime(serverInfo.getWarZone(), serverInfo.getStartTime(), curTime);
        long actStarttime = time[0];
        for (ActTopRanking ranking : topRankingList) {
            long rankId = RankActManager.getRankId(actConfig.getConfigId(), (byte) ranking.getType());
            String rankKey = RankActManager.getServerActRankKey(rankId, serverInfo.getServerId(), 1);
            Long myRank = Future.await(RedisTools.getMyRank(rankKey, userId + ""));
            if (myRank > 0) {
                response.putRankList(ranking.getType(), myRank.intValue());
            }
        }
        return response;
    }

    // CMD_GAME_RANKACT_GET_REWARD = 73204; // 领取冲榜活动奖励
    public static Object CMD_GAME_RANKACT_GET_REWARD(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        ServerInfo serverInfo = ServerManager.getServerInfo(userInfo.getServerId());
        CSGameRankactGetRewardRequest request = CSGameRankactGetRewardRequest.parseFrom(clientParam.getData());
        int configId = request.getConfigId();
        int rankType = request.getRankType();
        long curTime = TimeUtils.getCurTime();
        ActConfig actConfig = RankActManager.getActConfigByTopId(ActConfig.GROUP_ID_LOCAL, configId);
        if (actConfig == null) {
            return ErrorWord.NOT_DATA;
        }
        if (!actConfig.isInGetRewardTime(serverInfo.getWarZone(), serverInfo.getStartTime(), curTime)) {
            return ErrorWord.WRONG_STATUS;
        }
        CSGameRankactGetRewardResponse.Builder response = CSGameRankactGetRewardResponse.newBuilder();
        ActTopRanking ranking = RankActManager.getActTopRankingByType(actConfig.getRankList(), rankType);
        long rankId = RankActManager.getRankId(configId, (byte) rankType);
//        long yesterday = curTime - TimeUtils.DAY;
//        long[] time = actConfig.getConfigTime(serverInfo.getServerGroup(), serverInfo.getStartTime(), yesterday);
        String rankName = RankActManager.getServerActRankKey(rankId, serverInfo.getServerId(), 1);
        long myRank = 0;
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (rankType == ActTopRanking.RANK_TYPE_UNION_EXP) {
            if (userUnion.getUnionId() > 0) {
                myRank = Future.await(RedisTools.getMyRank(rankName, userUnion.getUnionId() + ""));
            }
        } else {
            myRank = Future.await(RedisTools.getMyRank(rankName, userId + ""));
        }
        if (myRank <= 0 || myRank > ranking.getList()) {
            return ErrorWord.INVALID_OPERATION; // 未上榜
        }

        RankReward rankReward = RankManager.getRankReward(ranking.getReward(), (int) myRank);
        if (rankReward == null) {
            return ErrorWord.NOT_DATA_2;
        }
        long round = 1;
        PBUserData.Builder pbUserData = response.getUserBuilder();
        if (rankType == ActTopRanking.RANK_TYPE_UNION_EXP) {
            UnionInfo unionInfo = UnionManager.getUnionInfo(userUnion.getUnionId());
            if (unionInfo == null) {
                return ErrorWord.NOT_DATA_1;
            }
            if (unionInfo.getMasterId() == userId) {
                RewardManager.addReward(userInfo, CommonUtils.takeReawrdItemFromStr(rankReward.getReward()), pbUserData, LogType.RANK_ACT_RANK_REWARD, myRank);
            } else {
                RewardManager.addReward(userInfo, CommonUtils.takeReawrdItemFromStr(rankReward.getReward2()), pbUserData, LogType.RANK_ACT_RANK_REWARD, myRank);
            }
        } else {
            RewardManager.addReward(userInfo, CommonUtils.takeReawrdItemFromStr(rankReward.getReward()), pbUserData, LogType.RANK_ACT_RANK_REWARD, myRank);
        }
        UserRankAct userActTopRank = RankActManager.getUserRankAct(userId, round, configId);
        if (userActTopRank == null) {
            userActTopRank = new UserRankAct(userId, round, configId);
            userActTopRank.doCreate();
        } else {
            userActTopRank.checkReset(round);
        }
        JsonArray rankGetArray = userActTopRank.getRankGetArray();
        if (Tool.isInList(rankGetArray, rankType)) {
            return ErrorWord.REPEATED_OPERATION; // 已领取过奖励
        }
        rankGetArray.add(rankType);
        userActTopRank.putRankGet(rankGetArray.toString());
        userActTopRank.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userActTopRank);
        return response;
    }

    // CMD_GAME_RANKACT_CROSS_LIST = 73205;// 获取跨服冲榜活动列表信息
    public static Object CMD_GAME_RANKACT_CROSS_LIST(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        ServerInfo serverInfo = ServerManager.getServerInfo(userInfo.getServerId());
        int localDays = RankActManager.getActDays(ActConfig.GROUP_ID_LOCAL);
        long curTime = TimeUtils.getCurTime();
        int serverOpenDays = TimeUtils.getDiffDay(serverInfo.getStartTime(), curTime) + 1;
        if (serverOpenDays < localDays) {
            return ErrorWord.WRONG_STATUS; // 未到参赛时间
        }
        JsonObject actInfo = RankActManager.isCrossRankAct(curTime);
        if (actInfo == null) {
            return ErrorWord.NOT_DATA_3; // 未到参赛时间
        }
        long round = actInfo.getLong("round");
        int actId = actInfo.getInteger("actid");
        long stime = actInfo.getLong("stime");
        ActConfig actConfig = RankActManager.getActConfig(actId);
        RankActGroup rankActGroup = RankActManager.getRankActGroup(serverInfo.getWarZone(), round);
        if (rankActGroup == null) {
            return ErrorWord.NOT_DATA_2;
        }
        JsonArray serverList = rankActGroup.getServerListArray();
        if (!Tool.isInList(serverList, serverInfo.getServerId())) {
            return ErrorWord.NOT_DATA_2; // 未加入分组
        }
        CSGameRankactCrossListRequest request = CSGameRankactCrossListRequest.parseFrom(clientParam.getData());
        CSGameRankactCrossListResponse.Builder response = CSGameRankactCrossListResponse.newBuilder();
        List<ActTopRanking> rankingList = RankActManager.getActTopRankingList(actConfig.getRankList());
        if (rankingList == null || rankingList.isEmpty()) {
            return ErrorWord.NOT_DATA;
        }
        for (ActTopRanking ranking : rankingList) {
            String userRankName = RankActManager.getCrossUserRankKey(ranking.getType(), serverInfo.getWarZone(), round);
            Long myRank = Future.await(RedisTools.getMyRank(userRankName, userId + ""));
            response.putMyRankList(ranking.getType(), myRank.intValue());
        }
        long etime = actInfo.getLong("etime");
        long endTime = etime - AllParam.RANK_ACT_REWARD_START_TIME;
        long closeTime = etime + AllParam.RANK_ACT_REWARD_END_HOUR * TimeUtils.HOUR;
        response.setStartTime(stime);
        response.setEndTime(endTime);
        response.setCloseTime(closeTime);
        return response;
    }

    // CMD_GAME_RANKACT_CROSS_INFO = 73206; // 获取跨服冲榜活动信息
    public static Object CMD_GAME_RANKACT_CROSS_INFO(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        CSGameRankactCrossInfoRequest request = CSGameRankactCrossInfoRequest.parseFrom(clientParam.getData());
        CSGameRankactCrossInfoResponse.Builder response = CSGameRankactCrossInfoResponse.newBuilder();
        int curAct = request.getCurAct();
        int type = request.getType();

        long curTime = TimeUtils.getCurTime();
        if (curAct == 0) {
            curTime = TimeUtils.getStartTimeOfDay(curTime) - TimeUtils.DAY;
        }
        JsonObject actInfo = RankActManager.isCrossRankAct(curTime);
        if (actInfo == null) {
            return ErrorWord.WRONG_STATUS;
        }

//        int stime = actInfo.getInteger("stime");
        int etime = actInfo.getInteger("etime");
//        int closetime = actInfo.getInteger("closetime");
        int configId = actInfo.getInteger("actid");
        String rankTime = actInfo.getString("stimeDay");
        long round = actInfo.getLong("round");

//        if (curTime < stime || curTime > closetime) {
//            return ErrorWord.STILL_IN_CDTIME; // 还未开赛
//        }
        ActConfig actConfig = RankActManager.getActConfigByTopId(ActConfig.GROUP_ID_GLOBAL, configId);
        if (actConfig == null) {
            return ErrorWord.NOT_DATA_2; // 没有配置
        }
        UserInfo userInfo = GameUser.getUserInfo(userId);
        ServerInfo serverInfo = ServerManager.getServerInfo(userInfo.getServerId());
        RankActGroup rankActGroup = RankActManager.getRankActGroup(serverInfo.getWarZone(), round);
        if (rankActGroup == null) {
            return ErrorWord.WRONG_STATUS; // 休赛
        }
        JsonArray serverList = rankActGroup.getServerListArray();
        if (!Tool.isInList(serverList, serverInfo.getServerId())) {
            return ErrorWord.STILL_IN_CDTIME;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
//        if (type == ActTopRanking.RANK_TYPE_UNION_EXP && userUnion.getUnionId() == 0) {
//            return ErrorWord.NOT_DATA_3;
//        }

        ActTopRanking actTopRanking = RankActManager.getActTopRankingByType(actConfig.getRankList(), type);
        if (actTopRanking == null) {
            return ErrorWord.NOT_DATA;
        }
        long rankId = RankActManager.getRankId(configId, (byte) type);
        String userRankName = RankActManager.getCrossUserRankKey(rankId, serverInfo.getWarZone(),round);
        JsonArray rankList = Future.await(RedisTools.getRankListByIndex(userRankName,0, actTopRanking.getList(),true));
        for (int i = 0; i < rankList.size(); i += 2) {
            long uid = Long.parseLong(rankList.getString(i));
            double score = Double.parseDouble(rankList.getString(i + 1));
            PBRankMember.Builder rankBuilder = null;
            if (type == ActTopRanking.RANK_TYPE_UNION_EXP) {
                rankBuilder = RankActManager.getUnionRankMember(uid, score);
            } else {
                rankBuilder = RankActManager.getRankMember(uid, score);
            }
            response.addRankList(rankBuilder);
        }
        Long myRank = null;
        if (type == ActTopRanking.RANK_TYPE_UNION_EXP) {
            if (userUnion.getUnionId() != 0) {
                myRank = Future.await(RedisTools.getMyRank(userRankName,String.valueOf(userUnion.getUnionId())));
                UnionActTopCrossRank unionActTopCrossRank = RankActManager.getUnionActTopCrossRank(userId,rankId, round);
                if (unionActTopCrossRank != null && unionActTopCrossRank.getActTime() == round) {
                    response.setMyRankScore(unionActTopCrossRank.getScore());
                    response.setMyMaxScore(unionActTopCrossRank.getMaxScore());
                }
            } else {
                myRank = 0L;
            }
        } else {
            myRank = Future.await(RedisTools.getMyRank(userRankName,String.valueOf(userId)));
            UserActTopCrossRank usercrossrank = RankActManager.getUserActTopCrossRank(userId,rankId, round);
            if (usercrossrank != null && usercrossrank.getActTime() == round) {
                response.setMyRankScore(usercrossrank.getScore());
                response.setMyMaxScore(usercrossrank.getMaxScore());
            }
        }
        response.setMyRank(myRank.intValue());
        return response;
    }

    // CMD_GAME_RANKACT_CROSS_GETREWARD = 73207; // 获取跨服冲榜活动奖励
    public static Object CMD_GAME_RANKACT_CROSS_GETREWARD(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        CSGameRankactCrossGetrewardRequest request = CSGameRankactCrossGetrewardRequest.parseFrom(clientParam.getData());
        int rankType = request.getRankType();
        CSGameRankactCrossGetrewardResponse.Builder response = CSGameRankactCrossGetrewardResponse.newBuilder();
        PBUserData.Builder pbUserData = response.getUserBuilder();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        ServerInfo serverInfo = ServerManager.getServerInfo(userInfo.getServerId());
        long curTime = TimeUtils.getCurTime();
        long todayStartTime = TimeUtils.getStartTimeOfDay(curTime);
        long yesterdayStartTime = todayStartTime - TimeUtils.DAY;

        JsonObject actInfo = RankActManager.isCrossRankAct(yesterdayStartTime);
        if (actInfo == null) {
            return ErrorWord.WRONG_STATUS;
        }
        long etime = actInfo.getLong("etime");
        long closetime = actInfo.getLong("closetime");
//        long stime = actInfo.getLong("stime");
        if (curTime < etime + 5 * TimeUtils.MINUTE || curTime > closetime) {
            return ErrorWord.WRONG_STATUS;
        }
        int actid = actInfo.getInteger("actid");
        ActConfig actConfig = RankActManager.getActConfigByTopId(ActConfig.GROUP_ID_GLOBAL, actid);
        if (actConfig == null) {
            return ErrorWord.NOT_DATA_2;
        }
        String stimeDay = actInfo.getString("stimeDay");
        long round = actInfo.getLong("round");
        RankActGroup rankActGroup = RankActManager.getRankActGroup(serverInfo.getWarZone(), round);
        if (rankActGroup == null) {
            return ErrorWord.STILL_IN_CDTIME;
        }
        if (!rankActGroup.containsServer(serverInfo.getServerId())) {
            return ErrorWord.STILL_IN_CDTIME;
        }
        ActTopRanking actTopRanking = RankActManager.getActTopRankingByType(actConfig.getRankList(), rankType);
        if (actTopRanking == null) {
            return ErrorWord.NOT_DATA;
        }
        long rankId = RankActManager.getRankId(actConfig.getConfigId(), (byte) rankType);
        UserCrossRankAct userActTopCrossRank = RankActManager.getUserCrossRankAct(userId, actConfig.getConfigId());
        if (userActTopCrossRank == null) {
            userActTopCrossRank = new UserCrossRankAct(userId, actConfig.getConfigId(), round);
            userActTopCrossRank.doCreate();
        } else {
            userActTopCrossRank.checkReset(round);
        }
        JsonArray rankGet = userActTopCrossRank.getRankGetArray();
        if (Tool.isInList(rankGet, rankType)) {
            return ErrorWord.REPEATED_OPERATION; // 已经领取过奖励
        }
        String rankKey = RankActManager.getCrossUserRankKey(rankId, serverInfo.getWarZone(), round);
        Long myRank = null;
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (rankType == ActTopRanking.RANK_TYPE_UNION_EXP) {
            if (userUnion.getUnionId() > 0) {
                myRank = Future.await(RedisTools.getMyRank(rankKey, userUnion.getUnionId() + ""));
            }
        } else {
            myRank = Future.await(RedisTools.getMyRank(rankKey, String.valueOf(userId)));
        }
        if (myRank == null || myRank > actTopRanking.getList()) {
            return ErrorWord.INVALID_OPERATION;
        }
        RankReward rankReward = RankManager.getRankReward(actTopRanking.getReward(), myRank.intValue());
        if (rankReward == null) {
            return ErrorWord.NOT_DATA;
        }
        if (rankType == ActTopRanking.RANK_TYPE_UNION_EXP) {
            UnionInfo unionInfo = UnionManager.getUnionInfo(userUnion.getUnionId());
            if (unionInfo == null) {
                return ErrorWord.NOT_DATA_1;
            }
            if (unionInfo.getMasterId() == userId) {
                RewardManager.addReward(userInfo, CommonUtils.takeReawrdItemFromStr(rankReward.getReward()), pbUserData, LogType.RANK_ACT_RANK_REWARD, myRank);
            } else {
                RewardManager.addReward(userInfo, CommonUtils.takeReawrdItemFromStr(rankReward.getReward2()), pbUserData, LogType.RANK_ACT_RANK_REWARD, myRank);
            }
        } else {
            RewardManager.addReward(userInfo, CommonUtils.takeReawrdItemFromStr(rankReward.getReward()), pbUserData, LogType.RANK_ACT_RANK_REWARD, myRank);
        }
        rankGet.add(rankType);
        userActTopCrossRank.putRankGet(rankGet.toString());
        userActTopCrossRank.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userActTopCrossRank);
        return response;
    }

    // CMD_GAME_RANKACT_TASK_REWARD = 73208; // 领取冲榜活动任务奖励
    public static Object CMD_GAME_RANKACT_TASK_REWARD(RequestParam clientParam) throws Exception {
        CSGameRankactTaskRewardRequest request = CSGameRankactTaskRewardRequest.parseFrom(clientParam.getData());
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        ServerInfo serverInfo = ServerManager.getServerInfo(userInfo.getServerId());
        int taskId = request.getTaskId();
        ConcurrentHashMap<Integer, ActConfig> configList = RankActManager.getActConfigList(ActConfig.GROUP_ID_LOCAL);
        if (configList == null || configList.isEmpty()) {
            return ErrorWord.NOT_DATA;
        }
        int day = TimeUtils.getDiffDay(serverInfo.getStartTime(), TimeUtils.getCurTime()) + 1;
        int allDay = RankActManager.getActDays(ActConfig.GROUP_ID_LOCAL);
        if (day > allDay) {
            return ErrorWord.TIMES_LACK;
        }
        ActConfig actConfig = RankActManager.getActConfig(day, configList, false);
        if (actConfig == null) {
            return ErrorWord.NOT_DATA_1;
        }
        int configId = actConfig.getConfigId();
        ActTask actTask = ActDaysManager.getActTask(taskId);
        int taskType = ActDaysManager.getTaskId(actTask.getTaskType(), actTask.getNum2());
        UserRankActTask userTask = RankActManager.getUserRankActTask(userId, 1, configId, taskType);
        if (userTask == null) {
            return ErrorWord.NOT_DATA_2;
        }
        UserRankAct userRankAct = RankActManager.getUserRankAct(userId, 1, configId);
        if (userRankAct == null) {
            userRankAct = new UserRankAct(userId, 1, configId);
            userRankAct.doCreate();
        }
        JsonArray taskGet = userRankAct.getTaskGetArray();
        if (Tool.isInList(taskGet, taskId)) {
            return ErrorWord.REPEATED_OPERATION; // 已经领取过奖励
        }
        if (userTask.getCurP() < actTask.getNum1()) {
            return ErrorWord.INVALID_OPERATION;
        }

        CSGameRankactTaskRewardResponse.Builder response = CSGameRankactTaskRewardResponse.newBuilder();
        PBUserData.Builder pbUserData = response.getUserBuilder();
        RewardManager.addReward(userInfo, actTask.getReward(), pbUserData, LogType.RANK_ACT_TASK_REWARD, taskId);
        taskGet.add(taskId);
        userRankAct.putTaskGet(taskGet.toString());
//        if (MainTaskManager.isResetNumByTaskType(actTask.getTaskType())) {
//            userTask.putCurP(0);// 某任务类型的进度值,是否在领取完奖励需要重置
//            userTask.update();
//            ProtoDataUtils.updatePBUserData(pbUserData, userTask);
//        }
        userRankAct.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userRankAct);
        return response;
    }

    // CMD_GAME_RANKACT_CROSS_TASK_REWARD = 73209; // 领取跨服冲榜活动任务奖励
    public static Object CMD_GAME_RANKACT_CROSS_TASK_REWARD(RequestParam clientParam) throws Exception {
        CSGameRankactCrossTaskRewardRequest request = CSGameRankactCrossTaskRewardRequest.parseFrom(clientParam.getData());
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        ServerInfo serverInfo = ServerManager.getServerInfo(userInfo.getServerId());
        int taskId = request.getTaskId();
        long curTime = TimeUtils.getCurTime();
        JsonObject actInfo = RankActManager.isCrossRankAct(curTime);
        if (actInfo == null) {
            return ErrorWord.STILL_IN_CDTIME;
        }
        int round = actInfo.getInteger("round");
        int configId = actInfo.getInteger("actid");
        RankActGroup group = RankActManager.getRankActGroup(serverInfo.getWarZone(), round);
        JsonArray serverList = group.getServerListArray();
        if (!Tool.isInList(serverList, serverInfo.getServerId())) {
            return ErrorWord.WRONG_STATUS;
        }
        ActConfig actConfig = RankActManager.getActConfig(configId);
        if (actConfig == null) {
            return ErrorWord.NOT_DATA;
        }
        ActTask actTask = ActDaysManager.getActTask(taskId);
        int taskType = ActDaysManager.getTaskId(actTask.getTaskType(), actTask.getNum2());
        UserCrossRankActTask userTask = RankActManager.getUserCrossRankActTask(userId, round, configId, taskType);
        if (userTask == null) {
            return ErrorWord.NOT_DATA_1;
        }
        userTask.checkReset(round);
        if (userTask.getCurP() < actTask.getNum1()) {
            return ErrorWord.INVALID_OPERATION;
        }

        UserCrossRankAct userRankAct = RankActManager.getUserCrossRankAct(userId, configId);
        if (userRankAct == null) {
            userRankAct = new UserCrossRankAct(userId, configId, round);
            userRankAct.doCreate();
        } else {
            userRankAct.checkReset(round);
        }
        JsonArray taskGet = userRankAct.getTaskGetArray();
        if (Tool.isInList(taskGet, taskId)) {
            return ErrorWord.REPEATED_OPERATION; // 已经领取过奖励
        }
        CSGameRankactCrossTaskRewardResponse.Builder response = CSGameRankactCrossTaskRewardResponse.newBuilder();
        PBUserData.Builder pbUserData = response.getUserBuilder();
        RewardManager.addReward(userInfo, actTask.getReward(), pbUserData, LogType.RANK_ACT_CROSS_TASK_REWARD, taskId);
        taskGet.add(taskId);
        userRankAct.putTaskGet(taskGet.toString());
//        if (MainTaskManager.isResetNumByTaskType(actTask.getTaskType())) {
//            userTask.putCurP(0);// 某任务类型的进度值,是否在领取完奖励需要重置
//            userTask.update();
//            ProtoDataUtils.updatePBUserData(pbUserData, userTask);
//        }
        userRankAct.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userRankAct);
        return response;
    }

    // CMD_GAME_RANKACT_RECHARGE_TASK_REWARD = 73210; // 领取充值任务奖励
    public static Object CMD_GAME_RANKACT_RECHARGE_TASK_REWARD(RequestParam clientParam) throws Exception {
        CSGameRankactRechargeTaskRewardRequest request = CSGameRankactRechargeTaskRewardRequest.parseFrom(clientParam.getData());
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        int taskId = request.getTaskId();
        ServerInfo serverInfo = ServerManager.getServerInfo(userInfo.getServerId());
        ConcurrentHashMap<Integer, ActConfig> configList = RankActManager.getActConfigList(ActConfig.GROUP_ID_LOCAL);
        if (configList == null || configList.isEmpty()) {
            return ErrorWord.NOT_DATA;
        }
        int day = TimeUtils.getDiffDay(serverInfo.getStartTime(), TimeUtils.getCurTime()) + 1;
        int allDay = RankActManager.getActDays(ActConfig.GROUP_ID_LOCAL);
        if (day > allDay) {
            return ErrorWord.TIMES_LACK;
        }
        ActConfig actConfig = RankActManager.getActConfig(day, configList, false);
        if (actConfig == null) {
            return ErrorWord.NOT_DATA_1;
        }
        int configId = actConfig.getConfigId();
        ActRechargeTask actTask = RankActManager.getActRechargeTask(taskId);
        if (actTask == null) {
            return ErrorWord.NOT_DATA;
        }
        int taskType = actTask.getTaskType();
        UserRechargeActTask userTask = RankActManager.getUserRechargeActTask(userId, configId, taskType);
        if (userTask == null) {
            return ErrorWord.NOT_DATA_2;
        }
        UserRankAct userRankAct = RankActManager.getUserRankAct(userId, 1, configId);
        if (userRankAct == null) {
            userRankAct = new UserRankAct(userId, 1, configId);
            userRankAct.doCreate();
        }
        JsonArray taskGet = userRankAct.getRechargeTaskGetArray();
        if (Tool.isInList(taskGet, taskId)) {
            return ErrorWord.REPEATED_OPERATION; // 已经领取过奖励
        }
        if (userTask.getCurP() < actTask.getNum()) {
            return ErrorWord.INVALID_OPERATION;
        }

        CSGameRankactRechargeTaskRewardResponse.Builder response = CSGameRankactRechargeTaskRewardResponse.newBuilder();
        PBUserData.Builder pbUserData = response.getUserBuilder();
        RewardManager.addReward(userInfo, actTask.getReward(), pbUserData, LogType.RANK_ACT_RECHARGE_TASK_REWARD, taskId);
        taskGet.add(taskId);
        userRankAct.putRechargeTaskGet(taskGet.toString());
        userRankAct.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userTask);
        ProtoDataUtils.updatePBUserData(pbUserData, userRankAct);
        return response;
    }

    // CMD_GAME_RANKACT_CROSS_RECHARGE_TASK_REWARD = 73211; // 领取跨服充值任务奖励
    public static Object CMD_GAME_RANKACT_CROSS_RECHARGE_TASK_REWARD(RequestParam clientParam) throws Exception {
        CSGameRankactCrossRechargeTaskRewardRequest request = CSGameRankactCrossRechargeTaskRewardRequest.parseFrom(clientParam.getData());
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        int taskId = request.getTaskId();
        ServerInfo serverInfo = ServerManager.getServerInfo(userInfo.getServerId());
        long curTime = TimeUtils.getCurTime();
//        long yesterday = curTime - TimeUtils.DAY;
        JsonObject actInfo = RankActManager.isCrossRankAct(curTime);
        if (actInfo == null) {
            return ErrorWord.STILL_IN_CDTIME;
        }
        int round = actInfo.getInteger("round");
        int configId = actInfo.getInteger("actid");
//        long endTime = actInfo.getLong("etime");
//        if (curTime < endTime) {
//            return ErrorWord.WRONG_STATUS;
//        }
        long closeTime = actInfo.getLong("closetime");
        if (curTime > closeTime) {
            return ErrorWord.NOT_DATA_4;
        }
        RankActGroup group = RankActManager.getRankActGroup(serverInfo.getWarZone(), round);
        JsonArray serverList = group.getServerListArray();
        if (!Tool.isInList(serverList, serverInfo.getServerId())) {
            return ErrorWord.WRONG_STATUS;
        }
        ActConfig actConfig = RankActManager.getActConfig(configId);
        if (actConfig == null) {
            return ErrorWord.NOT_DATA;
        }
        ActRechargeTask actTask = RankActManager.getActRechargeTask(taskId);
        if (actTask == null) {
            return ErrorWord.NOT_DATA;
        }
        int taskType = actTask.getTaskType();
        UserCrossRechargeActTask userTask = RankActManager.getUserCrossRechargeActTask(userId, configId, taskType);
        if (userTask == null) {
            return ErrorWord.NOT_DATA_1;
        }
        userTask.checkRound(round);
        if (userTask.getCurP() < actTask.getNum()) {
            return ErrorWord.INVALID_OPERATION;
        }

        UserCrossRankAct userRankAct = RankActManager.getUserCrossRankAct(userId, configId);
        if (userRankAct == null) {
            userRankAct = new UserCrossRankAct(userId, configId, round);
            userRankAct.doCreate();
        } else {
            userRankAct.checkReset(round);
        }
        JsonArray taskGet = userRankAct.getRechargeTaskGetArray();
        if (Tool.isInList(taskGet, taskId)) {
            return ErrorWord.REPEATED_OPERATION; // 已经领取过奖励
        }
        CSGameRankactCrossRechargeTaskRewardResponse.Builder response = CSGameRankactCrossRechargeTaskRewardResponse.newBuilder();
        PBUserData.Builder pbUserData = response.getUserBuilder();
        RewardManager.addReward(userInfo, actTask.getReward(), pbUserData, LogType.RANK_ACT_CROSS_RECHARGE_TASK_REWARD, taskId);
        taskGet.add(taskId);
        userRankAct.putRechargeTaskGet(taskGet.toString());
        userRankAct.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userTask);
        ProtoDataUtils.updatePBUserData(pbUserData, userRankAct);
        return response;
    }

    // CMD_GAME_RANKACT_SHOP_BUY = 73212; // 限时活动钻石兑换
    public static Object CMD_GAME_RANKACT_SHOP_BUY(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        CSGameRankactShopBuyRequest request = CSGameRankactShopBuyRequest.parseFrom(clientParam.getData());
        int shopId = request.getShopId();
        Shop shop = ShopManager.getShop(shopId);
        if (shop == null) {
            return ErrorWord.NOT_DATA;
        }
        int num = request.getCount();
        if (num <= 0 || num > 9999) {
            return ErrorWord.BAD_PARAM;
        }
        AtomicLong roundId = new AtomicLong();
        ActConfig actConfig = RankActManager.getActConfig(userInfo, roundId);
        if (actConfig == null) {
            return ErrorWord.NOT_DATA;
        }
        int[] shopIdArray = actConfig.getShopIdArray();
        if (!Tool.isInList(shopIdArray, shopId)) {
            return ErrorWord.NOT_DATA_1;
        }

        List<RewardItem> costItem = CommonUtils.takeReawrdItemFromStr(shop.getPrice());
        CommonUtils.multipleItemList(costItem, num);//数量 x N倍
        if (shop.getIsFree() == 0 && !BagManager.checkNeedItemNum(userInfo, costItem)) {// 非免费商品
            return ErrorWord.ITEM_LACK;// 道具不足
        }
        List<RewardItem> rewardItemList = CommonUtils.takeReawrdItemFromStr(shop.getReward());
        CommonUtils.multipleItemList(rewardItemList, num);//数量 x N倍

        CSGameRankactShopBuyResponse.Builder response = CSGameRankactShopBuyResponse.newBuilder();
        PBUserData.Builder pbUserData = response.getUserBuilder();
        int configId = actConfig.getConfigId();
        if (actConfig.getGroupId() == ActConfig.GROUP_ID_LOCAL) {
            UserRankActShop userRankActShop = RankActManager.getUserRankActShop(userId, configId, shopId);
            if (userRankActShop == null) {
                userRankActShop = new UserRankActShop(userId, configId, shopId, 0);
                userRankActShop.doCreate();
            }
            if (shop.getLimitNum() > 0 && userRankActShop.getNum() + num > shop.getLimitNum()) {
                return ErrorWord.ALREADY_MAX;
            }
            if (shop.getIsFree() == 0) {
                RewardManager.subReward(userInfo, costItem, pbUserData, LogType.RANK_ACT_SHOP_BUY, shopId);
            }
            RewardManager.addReward(userInfo, rewardItemList, pbUserData, LogType.RANK_ACT_SHOP_BUY, shopId);
            userRankActShop.addNum(num);
            userRankActShop.update();
            ProtoDataUtils.updatePBUserData(pbUserData, userRankActShop);
        } else {
            UserCrossRankActShop userRankActShop = RankActManager.getUserCrossRankActShop(userId, configId, shopId);
            if (userRankActShop == null) {
                userRankActShop = new UserCrossRankActShop(userId, configId, roundId.get(), shopId, 0);
                userRankActShop.doCreate();
            }
            userRankActShop.checkRound(roundId.get());
            if (shop.getLimitNum() > 0 && userRankActShop.getNum() + num > shop.getLimitNum()) {
                return ErrorWord.ALREADY_MAX;
            }
            if (shop.getIsFree() == 0) {
                RewardManager.subReward(userInfo, costItem, pbUserData, LogType.RANK_ACT_SHOP_BUY, shopId);
            }
            RewardManager.addReward(userInfo, rewardItemList, pbUserData, LogType.RANK_ACT_SHOP_BUY, shopId);
            userRankActShop.addNum(num);
            userRankActShop.update();
            ProtoDataUtils.updatePBUserData(pbUserData, userRankActShop);
        }
        return response;
    }

}
